package com.cheneyjoo.config;

import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.model.ResponseMessage;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class RouteConfig {
    private UrlConfig urlConfig;

    public RouteConfig() {
        urlConfig = new UrlConfig();
    }
    public ResponseMessage RegisterRoutes(JSONObject context) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,  IllegalArgumentException,InvocationTargetException, InstantiationException {
        Object url = Optional.ofNullable(context).map(s -> s.get("url")).orElse(null);
        Object tag = Optional.ofNullable(context).map(s -> s.get("tag")).orElse(null);

        if (Optional.ofNullable(url).isPresent() && Optional.ofNullable(tag).isPresent()) {
            Class<?> aClass = Class.forName(urlConfig.urlConfig.get(url));
            Optional<Method> routeMethod =  Arrays.stream(aClass.getDeclaredMethods()).filter(s->tag.toString().equals(s.getName())).findFirst();
            Map<String, Object> body = Optional.ofNullable(context.getJSONObject("body")).map(s->s.getInnerMap()).orElse(new HashMap<>());
            ResponseMessage invoke = null;
            if(routeMethod.isPresent()){
                Method invokeMethod=routeMethod.get();
                if (body.size() > 0) {
                    invoke = (ResponseMessage)(invokeMethod.invoke(aClass.getDeclaredConstructor().newInstance(), body.values().toArray()));
                } else {
                    invoke = (ResponseMessage)(invokeMethod.invoke(aClass.getDeclaredConstructor().newInstance()));
                }
            }
            return invoke;
        }
        return null;
    }
}
